package com.example.searchengine.controller;

import com.example.searchengine.model.Result;
import com.example.searchengine.model.ResultInfo;
import com.example.searchengine.model.Weight;
import com.example.searchengine.service.Index;
import org.ansj.domain.Term;
import org.ansj.splitWord.analysis.ToAnalysis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@RestController
public class Search {
    public static ArrayList<Result> results = new ArrayList<>();
    public static ArrayList<Weight> weights = new ArrayList<>();
    @RequestMapping("/search")
    public static ArrayList<Result> search(String query){
        List<Term> terms = ToAnalysis.parse(query).getTerms();
        for (Term term:terms) {
            String key = term.getName();
            ArrayList<Weight> list = Index.findKey(key);
            //遍历分词结果集合加入到总集合中
            if (list != null){
                weights.addAll(list);
            }
        }
        //对结果进行排序
        weights.sort(new Comparator<Weight>() {
            @Override
            public int compare(Weight o1, Weight o2) {
                return o2.getWeight() - o1.getWeight();
            }
        });
        //封装结果
        for (Weight weight : weights){
            ResultInfo resultInfo = Index.findId(weight.getId());
            Result result = new Result();
            result.setTitle(resultInfo.getTitle());
            result.setUrlOne(resultInfo.getUrl());
            result.setUrlTwo(resultInfo.getUrl());
            String count = getCount(resultInfo.getCount(),weight.getWord());
            result.setCount(count);
            results.add(result);
        }
        System.out.println("返回响应");
        return results;
    }

    private static String getCount(String count,String word) {
        int firstPos = count.toLowerCase().indexOf(word);
        if (firstPos == -1){
            return "";
        }
        int start = firstPos > 60? firstPos - 60:0;
        if (firstPos + 120 > count.length()){
            return count.substring(start);
        }else{
            return count.substring(start,firstPos+120);
        }
    }
}
